<template>
  <div class="detail-header">
    <!-- 悬浮返回按钮 -->
    <div v-show="showBtn" class="header-back" @click="goBack()">
      <i class="iconfont iconfanhuijiantou"></i>
    </div>
    <!-- 导航栏 -->
    <div v-show="!showBtn" class="header-bar" :style="opacityStyle">
      <i class="iconfont iconfanhuijiantou back-icon" @click="goBack()"></i>
      {{ title }}
    </div>
    <!-- 占位符 -->
    <div v-show="!showBtn && placeholder" class="placeholder"></div>
  </div>
</template>

<script>
export default {
  name: 'DetailHeader',
  props: {
    // 是否占位：防止高度塌陷
    placeholder: {
      type: Boolean,
      default: false,
    },
    // 标题
    title: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      showBtn: true,
      // 渐隐渐现效果
      opacityStyle: {
        opacity: 0,
      },
    }
  },
  mounted() {
    // 监听滚动事件
    window.addEventListener('scroll', this.handleScroll)
  },
  destroyed() {
    // 移除滚动事件
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    handleScroll() {
      const top = document.documentElement.scrollTop // 滚动距离顶部的距离
      if (top > 60) {
        let opacity = top / 140
        opacity = opacity > 1 ? 1 : opacity
        this.opacityStyle = { opacity }
        this.showBtn = false
      } else {
        this.showBtn = true
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.detail-header {
  .header-back {
    position: absolute;
    left: 0.1rem;
    top: 0.1rem;
    width: 0.4rem;
    height: 0.4rem;
    line-height: 0.4rem;
    text-align: center;
    border-radius: 0.2rem;
    background: rgba(0, 0, 0, 0.8);
    z-index: 9;
    color: #fff;
  }
  .header-bar {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    z-index: 9;
    left: 0;
    height: 0.43rem;
    line-height: 0.43rem;
    text-align: center;
    color: #fff;
    background: rgba($color: $green, $alpha: 0.8);
    font-size: 0.16rem;
    .back-icon {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 9;
      width: 0.32rem;
      text-align: center;
      font-size: 0.18rem;
    }
  }
  .placeholder {
    height: 0.43rem;
  }
}
</style>
